import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:mi_mang_flutter/model/daily_word_model.dart';
import 'package:mi_mang_flutter/page/collection/collection_page_provider.dart';
import 'package:mi_mang_flutter/provider/view.dart';
import 'package:mi_mang_flutter/res/dimens.dart';
import 'package:mi_mang_flutter/res/styles.dart';
import 'package:mi_mang_flutter/utils/formDate.dart';
import 'package:mi_mang_flutter/utils/image_utils.dart';
import 'package:mi_mang_flutter/utils/locale_util.dart';
import 'package:mi_mang_flutter/widget/widget_no_data.dart';
import 'package:provider/provider.dart';

class CollectionPage extends StatefulWidget {
  CollectionPage({Key? key}) : super(key: key);

  @override
  _CollectionPageState createState() => _CollectionPageState();
}

class _CollectionPageState extends State<CollectionPage>
    with AutomaticKeepAliveClientMixin {
  CollectionPageProvider? _provider;

  GlobalKey _easyRefreshKey = GlobalKey();
  ScrollController _scrollController = ScrollController();
  EasyRefreshController _controller = EasyRefreshController();

  @override
  void initState() {
    super.initState();
    _provider = CollectionPageProvider();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(i18n(context).collect),
        centerTitle: true,
        actions: <Widget>[
          ChangeNotifierProvider.value(
            value: _provider,
            child: Consumer<CollectionPageProvider>(
              builder: (_, provider, __) => IconButton(
                icon: Icon(
                    provider.isSingle ? Icons.dashboard : Icons.view_agenda),
                onPressed: provider.chageCrossAxisCount,
              ),
            ),
          ),
        ],
      ),
      body: ViewWidget(
        model: _provider,
        embeddedEmpty: true,
        builder: (context, CollectionPageProvider provider, _) {
          return EasyRefresh(
            key: _easyRefreshKey,
            scrollController: _scrollController,
            controller: _controller,
            child: CustomScrollView(
              slivers: [
                !provider.isFirstLoad && provider.isEmpty
                    ? const SliverFillRemaining(child: WidgetNoData())
                    : SliverToBoxAdapter(
                        child: GridView.builder(
                          physics: NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          padding: EdgeInsets.all(Dimens.gapDp15),
                          itemCount: provider.list?.length ?? 0,
                          gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: provider.crossAxisCount,
                            childAspectRatio: 0.618,
                            crossAxisSpacing: Dimens.gapDp15,
                            mainAxisSpacing: Dimens.gapDp15,
                          ),
                          itemBuilder: (context, index) {
                            DailyWordModel item = provider.list![index];
                            return _buildItem(provider, item);
                          },
                        ),
                      ),
              ],
            ),
            onRefresh: provider.onRefresh,
            onLoad: provider.isLoadMore ? provider.onLoad : null,
          );
        },
      ),
    );
  }

  Widget _buildItem(CollectionPageProvider provider, DailyWordModel model) {
    // 防止日期为空时报错(默认当前日期)
    model.publishTime ??= DateTime.now();
    var monthStr = formatDate(model.publishTime, [M]);
    return loadNetworkAssetImage(
      model.imageUrl,
      fit: BoxFit.cover,
      child: Stack(
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
                border: Border.all(color: Colors.white, width: 1.0)),
            margin: EdgeInsets.all(
                provider.isSingle ? Dimens.gapDp15 : Dimens.gapDp10),
            padding: EdgeInsets.all(
                provider.isSingle ? Dimens.gapDp5 : Dimens.gapDp3),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  "${model.publishTime?.day ?? '--'}",
                  textScaler: TextScaler.linear(provider.textScaleFactor),
                  style: Theme.of(context).textTheme.displayLarge!.copyWith(
                        height: 1.0,
                        color: Colors.white,
                      ),
                ),
                Text(
                  "$monthStr ${model.publishTime?.year ?? '--'}",
                  textScaler: TextScaler.linear(provider.textScaleFactor),
                  style: Theme.of(context).textTheme.bodyMedium!.copyWith(
                        color: Colors.white,
                      ),
                ),
              ],
            ),
          ),
          Positioned(
            left: provider.isSingle ? Dimens.gapDp20 : Dimens.gapDp15,
            right: provider.isSingle ? Dimens.gapDp20 : Dimens.gapDp15,
            bottom: provider.isSingle ? Dimens.gapDp20 : Dimens.gapDp15,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Gaps.vGap12,
                Text(
                  model.content ?? "谁的青春不迷茫",
                  textScaler: TextScaler.linear(provider.textScaleFactor),
                  style: Theme.of(context).textTheme.titleMedium!.copyWith(
                        height: 1.2,
                        color: Colors.white,
                      ),
                ),
                Gaps.vGap6,
                Container(
                  alignment: Alignment.centerRight,
                  child: Text(
                    "—— ${model.source ?? '米茫'}",
                    textScaler: TextScaler.linear(provider.textScaleFactor),
                    style: Theme.of(context).textTheme.bodyMedium!.copyWith(
                          color: Colors.white,
                        ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    _controller.dispose();
    _provider!.dispose();
    super.dispose();
  }
}
